/*
 * show_main.cpp
 *
 *  Created on: Apr 30, 2011
 *      Author: tqlong
 */

#include <boost/program_options.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <armadillo>
#include <QtGui>

#include "common/common.h"
#include "show_mainwindow.h"
#include "viewer/viewer.h"
#include "viewer/kdtree_viewer.h"

namespace po = boost::program_options;
po::options_description desc("Allowed options");
po::variables_map vm;

std::string in, out, query, prob, format;

void process_options(int argc, char**  argv);
int doJob(QApplication& app);

void usage()
{
  std::cout << desc << "\n";
  exit(0);
}

int main(int argc, char** argv)
{
  process_options(argc, argv);
  if (vm.count("help"))
    usage();

  boost::posix_time::ptime time_start(boost::posix_time::microsec_clock::local_time());

  QApplication app(argc, argv);
  int retval = doJob(app);

  boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());
  boost::posix_time::time_duration duration(time_end - time_start);
  std::cerr << "Duration = " << duration << "\n";
  return retval;
}

void process_options(int argc, char** argv)
{
  desc.add_options()
    ("help", "produce this usage")
    ("in", po::value<std::string>(&in)->default_value(""), "file contains input")
    ("q", po::value<std::string>(&query)->default_value(""), "query file")
    ("out", po::value<std::string>(&out)->default_value(""), "output file")
    ("prob", po::value<std::string>(&prob)->default_value(""), "problem: view, search")
    ("format", po::value<std::string>(&format)->default_value("txt"), "format: txt, bin, raw")
    ("number", "draw point index")
    ;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);
}

int doJob(QApplication& app)
{
  Viewer* viewer = NULL;
  if (prob == "view") {
    if (in.empty()) usage();
    viewer = new Viewer(in, format);
  }
  else if (prob == "kdtree") {
    if (in.empty()) usage();
    if (out.empty()) usage();
    viewer = new KDTreeViewer(in, out, format);
  }
  else if (prob == "search") {
    if (in.empty()) usage();
    if (query.empty()) usage();
    if (out.empty()) usage();
    bool number = vm.count("number");
    viewer = new KNNViewer(in, query, out, format, number);
  }
  else {
    Log::m_log << "specify a problem" << endl << endl;
    usage();
  }

  MainWindow w(viewer);
  w.setWindowTitle("Show results "+QString::fromStdString(prob)
                  + " in=" + QString::fromStdString(in)
                  + " out=" + QString::fromStdString(out)
                  + " q=" + QString::fromStdString(query)
                  + " format=" + QString::fromStdString(format)
                  );
//  w.resize(QSize(900, 950));
  w.show();

  int retval = app.exec();
  delete viewer;
  return retval;
}
